﻿using ProjectScheduling_web.model;
using ProjectScheduling_web.model.Enums;

namespace ProjectScheduling_web.dao
{
    public class InvoiceDao : BaseDao<Invoice>
    {
        public static readonly InvoiceDao Base = new();
        public PageData<Invoice> Search(int page, int row, string? name, string? startTime, string? endTime)
        {
            _ = DateTime.TryParse(startTime, out DateTime _st);
            _ = DateTime.TryParse(endTime, out DateTime _et);
            int total = 0;
            var data = Db.Queryable<Invoice>()
                .WhereIF(!string.IsNullOrEmpty(name), x => x.Name != null && x.Name.Contains(name??""))
                .WhereIF(!string.IsNullOrEmpty(startTime), x => x.InvoiceDate.Date >= _st.Date)
                .WhereIF(!string.IsNullOrEmpty(endTime), x => x.InvoiceDate.Date <= _et.Date)
                .OrderByDescending(x => x.Id)
                .ToPageList(page, row, ref total);
            return new PageData<Invoice>()
            {
                Items = data,
                Total = total
            };
        }
        public Invoice? Detail(int id)
        {
            var obj = Db.Queryable<Invoice>()
                .Where(x => x.Id == id)
                .First();
            if (obj == null) return null;
            var list = Db.Queryable<FileMsg>()
                .Where(x => x.PId == id && x.MsgType == EnumMsgType.开票)
                .ToList();
            var products = Db.Queryable<InvoiceProduct>()
                .Where(x => x.InvoiceId == id)
                .ToList();
            obj.Files = list;
            obj.Products = products;
            return obj;
        }
        public void Remove(int id)
        {
            Db.Deleteable<InvoiceProduct>().Where(x => x.InvoiceId == id).ExecuteCommand();
            Db.Deleteable<Invoice>().Where(x => x.Id == id).ExecuteCommand();
            Db.Deleteable<FileMsg>().Where(x => x.PId == id && x.MsgType == EnumMsgType.开票).ExecuteCommand();
        }
    }
}
